package com.tanhua.mongo.api;

import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.mongo.utils.IdWorker;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: cl
 * @Date: 2022/5/11 - 05 - 11
 * @Description:
 */

/**
 * 小视频服务
 */
@DubboService
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    /**
     * 发送小视频
     *
     * @param video
     * @return
     */
    @Override
    public String send(Video video) {

        video.setCreated(System.currentTimeMillis());
        video.setVid(idWorker.getNextId("video"));

        mongoTemplate.save(video);
        return video.getId().toHexString();
    }

    /**
     * 通过vid查询小视频
     *
     * @param vids
     * @return
     */
    @Override
    public List<Video> getByVids(List<Long> vids) {
        Query query = Query.query(Criteria.where("vid").in(vids))
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query, Video.class);
    }

    /**
     * 分页查询小视频
     *
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Video> page(int page, Integer pagesize) {

        Query query = new Query().skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query, Video.class);
    }

    /**
     * 根据用户id查询所有小视频
     *
     * @param page
     * @param pagesize
     * @param uid
     * @return
     */
    @Override
    public PageResult getVideosByUid(Integer page, Integer pagesize, Long uid) {
        //1、创建条件
        Criteria criteria = Criteria.where("userId").is(uid);
        //2、查询数据总条数
        long count = mongoTemplate.count(Query.query(criteria), Video.class);
        //3、查询数据详情
        List<Video> videos = mongoTemplate.find(Query.query(criteria).skip((page - 1) * pagesize).limit(pagesize)
                        .with(Sort.by(Sort.Order.desc("created"))),
                Video.class);

        List<VideoVo> vos = new ArrayList<>();
        for (Video video : videos) {
            VideoVo init = VideoVo.init(new UserInfo(), video);
            vos.add(init);
        }

        return new PageResult(page, pagesize, count, vos);
    }
}
